#include "U2EGLContext.h"

#include "U2Exception.h"
#include "U2EGLSupport.h"
#include "U2Root.h"
#include "U2GLESRenderSystem.h"


U2EG_NAMESPACE_USING


U2EGLContext::U2EGLContext(EGLDisplay eglDisplay,
						const U2EGLSupport* glsupport,
                       ::EGLConfig glconfig,
                       ::EGLSurface drawable)
: mGLSupport(glsupport)
, mDrawable(drawable)
, mContext(0)
, mConfig(glconfig)
, mEglDisplay(eglDisplay)
{
	assert(drawable);
    GLESRenderSystem* renderSystem =
        static_cast<GLESRenderSystem*>(U2Root::getSingleton().getRenderSystem());
    U2EGLContext* mainContext =
        static_cast<U2EGLContext*>(renderSystem->_getMainContext());
    ::EGLContext shareContext = (::EGLContext) 0;

    if (mainContext)
    {
        shareContext = mainContext->mContext;
    }

    mContext = mGLSupport->createNewContext(eglDisplay, mConfig, shareContext);

    if (!mContext)
    {
        U2_EXCEPT(U2Exception::ERR_RENDERINGAPI_ERROR,
                    "Unable to create a suitable EGLContext",
                    "EGLContext::EGLContext");
    }
}

U2EGLContext::~U2EGLContext()
{
    GLESRenderSystem *rs =
        static_cast<GLESRenderSystem*>(U2Root::getSingleton().getRenderSystem());

    eglDestroyContext(mEglDisplay, mContext);
    rs->_unregisterContext(this);
}

void U2EGLContext::setCurrent()
{
    EGLBoolean ret = eglMakeCurrent(mEglDisplay,
                                    mDrawable, mDrawable, mContext);
    if (!ret)
    {
        U2_EXCEPT(U2Exception::ERR_RENDERINGAPI_ERROR,
                    "Fail to make context current",
                    __FUNCTION__);
    }
}

void U2EGLContext::endCurrent()
{
	eglMakeCurrent(mEglDisplay, 0, 0, 0);
}

EGLSurface U2EGLContext::getDrawable() const
{
	return mDrawable;
}
